<script setup lang="ts">
import type { CaptchaVerification } from '../types'
import type { CaptchaCheckData } from '@/types/data'
import { checkCaptcha, getCaptcha } from '@/api/common/captcha'
import { aesEncrypt } from '@/utils/crypto'

defineOptions({
  name: 'VerifySlide',
})

const { type = '1', mode = 'fixed', space = 5, explain = '向右滑动完成验证', imgSize = { width: '310px', height: '155px' }, blockSize = { width: '50px', height: '50px' }, barSize = { width: '310px', height: '40px' } } = defineProps<{
  type?: string
  mode?: string
  space?: number
  explain?: string
  imgSize?: {
    width: string
    height: string
  }
  blockSize?: {
    width: string
    height: string
  }
  barSize?: {
    width: string
    height: string
  }
}>()

const emit = defineEmits<{
  (e: 'closeBox'): void
  (e: 'setClickShow', show: boolean): void
  (e: 'success', data: CaptchaVerification): void
}>()

const verifySlideRef = useTemplateRef<any>('verify-slide')
const secretKey = ref('')
const passFlag = ref(false) // 是否通过的标识
const backImgBase = ref('') // 验证码背景图片
const blockBackImgBase = ref('') // 验证滑块的背景图片
const backToken = ref('') // 后端返回的唯一token值
const startMoveTime = ref<number>(0) // 移动开始的时间
const endMovetime = ref<number>(0) // 移动结束的时间
const tipWords = ref('')
const text = ref('')
const finishText = ref('')
const setSize = reactive({
  imgHeight: '0',
  imgWidth: '0',
  barHeight: '0',
  barWidth: '0',
})
const moveBlockLeft = ref('')
const leftBarWidth = ref<string | undefined>(undefined)
// 移动中样式
const moveBlockBackgroundColor = ref<string | undefined>(undefined)
const leftBarBorderColor = ref('#ddd')
const iconColor = ref<string | undefined>(undefined)
const iconClass = ref('icon-right')
const status = ref(false) // 鼠标状态
const isEnd = ref(false) // 是够验证完成
const showRefresh = ref(true)
const transitionLeft = ref('')
const transitionWidth = ref('')
const startLeft = ref(0)

const barArea = computed(() => {
  return verifySlideRef.value?.querySelector('.verify-bar-area')
})

function resetSize() {
  // 图片的宽度、高度，移动条的宽度、高度
  let imgWidth, imgHeight, barWidth, barHeight
  const parentWidth = verifySlideRef.value.parentNode.offsetWidth || window.offsetWidth
  const parentHeight = verifySlideRef.value.parentNode.offsetHeight || window.offsetHeight
  if (imgSize.width.includes('%')) {
    imgWidth = `${parentWidth * (Number.parseInt(imgSize.width) / 100)}px`
  }
  else {
    imgWidth = imgSize.width
  }

  if (imgSize.height.includes('%')) {
    imgHeight = `${parentHeight * (Number.parseInt(imgSize.height) / 100)}px`
  }
  else {
    imgHeight = imgSize.height
  }

  if (barSize.width.includes('%')) {
    barWidth = `${parentWidth * (Number.parseInt(barSize.width) / 100)}px`
  }
  else {
    barWidth = barSize.width
  }

  if (barSize.height.includes('%')) {
    barHeight = `${parentHeight * (Number.parseInt(barSize.height) / 100)}px`
  }
  else {
    barHeight = barSize.height
  }

  return {
    imgWidth,
    imgHeight,
    barWidth,
    barHeight,
  }
}
function init() {
  text.value = explain
  // TODO 先生成uuid
  // TODO 生成图片
  nextTick(() => {
    getPicture()
    if (verifySlideRef.value) {
      const { imgWidth, imgHeight, barWidth, barHeight } = resetSize()
      setSize.imgWidth = imgWidth
      setSize.imgHeight = imgHeight
      setSize.barWidth = barWidth
      setSize.barHeight = barHeight
    }
  })
  window.removeEventListener('touchmove', (e) => {
    move(e)
  })
  window.removeEventListener('mousemove', (e) => {
    move(e)
  })

  // 鼠标松开
  window.removeEventListener('touchend', () => {
    end()
  })
  window.removeEventListener('mouseup', () => {
    end()
  })

  window.addEventListener('touchmove', (e) => {
    move(e)
  })
  window.addEventListener('mousemove', (e) => {
    move(e)
  })

  // 鼠标松开
  window.addEventListener('touchend', () => {
    end()
  })
  window.addEventListener('mouseup', () => {
    end()
  })
}

function start(e: any) {
  e = e || window.event
  let x
  if (!e.touches) {
    // 兼容PC端
    x = e.clientX
  }
  else {
    x = e.touches[0].pageX
  }

  if (barArea.value) {
    startLeft.value = Math.floor(x - barArea.value.getBoundingClientRect().left)
    startMoveTime.value = Date.now() // 开始滑动的时间
    if (isEnd.value === false) {
      text.value = ''
      moveBlockBackgroundColor.value = '#337ab7'
      leftBarBorderColor.value = '#337AB7'
      iconColor.value = '#fff'
      e.stopPropagation()
      status.value = true
    }
  }
}

function move(e: any) {
  e = e || window.event
  let x
  if (status.value && isEnd.value === false) {
    if (!e.touches) {
      // 兼容PC端
      x = e.clientX
    }
    else {
      // 兼容移动端
      x = e.touches[0].pageX
    }
    if (barArea.value) {
      const bar_area_left = barArea.value.getBoundingClientRect().left
      let move_block_left = x - bar_area_left // 小方块相对于父元素的left值
      if (move_block_left >= (barArea.value as HTMLElement).offsetWidth - Number.parseInt(`${Number.parseInt(blockSize.width) / 2}`) - 2) {
        move_block_left = (barArea.value as HTMLElement).offsetWidth - Number.parseInt(`${Number.parseInt(blockSize.width) / 2}`) - 2
      }
      if (move_block_left <= 0) {
        move_block_left = Number.parseInt(`${Number.parseInt(blockSize.width) / 2}`)
      }
      // 拖动后小方块的left值
      moveBlockLeft.value = `${move_block_left - startLeft.value}px`
      leftBarWidth.value = `${move_block_left - startLeft.value}px`
    }
  }
}

function end() {
  endMovetime.value = Date.now()
  // 判断是否重合
  if (status.value && isEnd.value === false) {
    let moveLeftDistance = Number.parseInt((moveBlockLeft.value || '').replace('px', ''))
    moveLeftDistance = (moveLeftDistance * 310) / Number.parseInt(setSize.imgWidth)
    const data: CaptchaCheckData = {
      pointJson: secretKey.value
        ? aesEncrypt(JSON.stringify({ x: moveLeftDistance, y: 5.0 }), secretKey.value)
        : JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
      token: backToken.value,
      clientUid: localStorage.getItem('slider')!,
      ts: Date.now(),
    }

    checkCaptcha(data).then((res) => {
      if (res.repCode === '0000') {
        moveBlockBackgroundColor.value = '#5cb85c'
        leftBarBorderColor.value = '#5cb85c'
        iconColor.value = '#fff'
        iconClass.value = 'icon-check'
        showRefresh.value = false
        isEnd.value = true
        if (mode === 'pop') {
          setTimeout(() => {
            emit('setClickShow', false)
            refresh()
          }, 1500)
        }
        passFlag.value = true
        tipWords.value = `${((endMovetime.value - startMoveTime.value) / 1000).toFixed(2)}s验证成功`
        const captchaVerification = secretKey.value
          ? aesEncrypt(`${backToken.value}---${JSON.stringify({ x: moveLeftDistance, y: 5.0 })}`, secretKey.value)
          : `${backToken.value}---${JSON.stringify({ x: moveLeftDistance, y: 5.0 })}`
        setTimeout(() => {
          tipWords.value = ''
          emit('closeBox')
          emit('success', { captchaVerification })
        }, 1000)
      }
      else {
        moveBlockBackgroundColor.value = '#d9534f'
        leftBarBorderColor.value = '#d9534f'
        iconColor.value = '#fff'
        iconClass.value = 'icon-close'
        passFlag.value = false
        setTimeout(() => {
          refresh()
        }, 1000)
        tipWords.value = '验证失败'
        setTimeout(() => {
          tipWords.value = ''
        }, 1000)
      }
    })
    status.value = false
  }
}

function refresh() {
  showRefresh.value = true
  finishText.value = ''

  transitionLeft.value = 'left .3s'
  moveBlockLeft.value = '0'

  leftBarWidth.value = undefined
  transitionWidth.value = 'width .3s'

  leftBarBorderColor.value = '#ddd'
  moveBlockBackgroundColor.value = '#fff'
  iconColor.value = '#000'
  iconClass.value = 'icon-right'
  isEnd.value = false

  getPicture()
  setTimeout(() => {
    transitionWidth.value = ''
    transitionLeft.value = ''
    text.value = explain
  }, 300)
}

function getPicture() {
  const data = {
    clientUid: localStorage.getItem('slider'),
    ts: Date.now(), // 现在的时间戳
  }

  getCaptcha(data).then((res) => {
    if (res.repCode === '0000') {
      backImgBase.value = res.repData.originalImageBase64
      blockBackImgBase.value = res.repData.jigsawImageBase64
      backToken.value = res.repData.token
      secretKey.value = res.repData.secretKey
    }
    else {
      tipWords.value = res.repMsg
    }
  })
}

watch(
  () => type,
  () => {
    init()
  },
  { immediate: true },
)
onMounted(() => {
  // 禁止拖拽
  if (verifySlideRef.value) {
    verifySlideRef.value.onselectstart = function () {
      return false
    }
  }
})
</script>

<template>
  <div ref="verify-slide" style="position: relative;">
    <div v-if="type === '2'" class="verify-img-out" :style="{ height: `${parseInt(setSize.imgHeight) + space}px` }">
      <div class="verify-img-panel" :style="{ width: setSize.imgWidth, height: setSize.imgHeight }">
        <img :src="`data:image/png;base64,${backImgBase}`" alt="" style=" display: block;width: 100%; height: 100%;">
        <div v-show="showRefresh" class="verify-refresh" @click="refresh">
          <i class="iconfont icon-refresh" />
        </div>
        <transition name="tips">
          <span v-if="tipWords" class="verify-tips" :class="passFlag ? 'suc-bg' : 'err-bg'">{{ tipWords }}</span>
        </transition>
      </div>
    </div>
    <!-- 公共部分 -->
    <div
      class="verify-bar-area"
      :style="{ 'width': setSize.imgWidth, 'height': barSize.height, 'line-height': barSize.height }"
    >
      <span class="verify-msg" v-text="text" />
      <div
        class="verify-left-bar" :style="{
          'width': leftBarWidth !== undefined ? leftBarWidth : barSize.height,
          'height': barSize.height,
          'border-color': leftBarBorderColor,
          'transition': transitionWidth,
        }"
      >
        <span class="verify-msg" v-text="finishText" />
        <div
          class="verify-move-block" :style="{
            'width': barSize.height,
            'height': barSize.height,
            'background-color': moveBlockBackgroundColor,
            'left': moveBlockLeft,
            'transition': transitionLeft,
          }" @touchstart="start" @mousedown="start"
        >
          <i class="iconfont verify-icon" :class="[iconClass]" :style="{ color: iconColor }" />
          <div
            v-if="type === '2'" class="verify-sub-block" :style="{
              'width': `${Math.floor((parseInt(setSize.imgWidth) * 47) / 310)}px`,
              'height': setSize.imgHeight,
              'top': `-${parseInt(setSize.imgHeight) + space}px`,
              'background-size': `${setSize.imgWidth} ${setSize.imgHeight}`,
            }"
          >
            <img
              :src="`data:image/png;base64,${blockBackImgBase}`" alt=""
              style=" display: block;width: 100%; height: 100%; -webkit-user-drag: none;"
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
